package com.bong.panpan.bongcharttools.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.bong.panpan.bongcharttools.R;
import com.bong.panpan.bongcharttools.custom.Constant;
import com.bong.panpan.bongcharttools.custom.MyUtil;
import com.bong.panpan.bongcharttools.custom.UserInfoRecord;

import java.io.File;
import java.util.ArrayList;

public class UserInfoActivity extends Activity implements View.OnClickListener {

    private ArrayList<EditText> editTexts = new ArrayList<>();
    private ArrayList<RadioGroup> radioGroups = new ArrayList<>();
    private ArrayList<RadioButton> radioButtons = new ArrayList<>();
    private ArrayList<CheckBox> checkBoxes = new ArrayList<>();
    private ArrayList<Button> buttons = new ArrayList<>();
    UserInfoRecord record;
    String recordPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);
        setTitle(getIntent().getStringExtra("title"));
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getViews((ViewGroup) findViewById(R.id.linear));
        Log.i("editTexts", "" + editTexts.size());
        Log.i("radioGroups", "" + radioGroups.size());
        Log.i("radioButtons", "" + radioButtons.size());
        Log.i("checkBoxes", "" + checkBoxes.size());
        Log.i("buttons", "" + buttons.size());
        for (int i = 0; i < buttons.size(); i++) {
            buttons.get(i).setOnClickListener(this);
        }
        recordPath = getIntent().getStringExtra("recordPath");
        if (recordPath == null)
            record = new UserInfoRecord();
        else {
            record = UserInfoRecord.load(recordPath);
            if (record == null)
                record = new UserInfoRecord();
            else
                loadData();
        }
        if (recordPath == null)
            editTexts.get(1).setText(String.format("%04d", getIntent().getIntExtra("adviseNum", 1)));
    }

    private void getViews(ViewGroup viewGroup) {
        if (viewGroup == null) {
            return;
        }
        int count = viewGroup.getChildCount();
        for (int i = 0; i < count; i++) {
            View view = viewGroup.getChildAt(i);
            if (view instanceof EditText) {
                editTexts.add((EditText) view);
            } else if (view instanceof RadioButton) {
                radioButtons.add((RadioButton) view);
            } else if (view instanceof CheckBox) {
                checkBoxes.add((CheckBox) view);
            } else if (view instanceof Button) {
                buttons.add((Button) view);
            } else if (view instanceof ViewGroup) {
                // 若是布局控件（LinearLayout或RelativeLayout）,继续查询子View
                if (view instanceof RadioGroup)
                    radioGroups.add((RadioGroup) view);
                getViews((ViewGroup) view);
            }
        }
    }

    @Override
    public void onClick(View v) {
        if (!(v instanceof Button))
            return;
        Button button = (Button) v;
        if ("取消".equals(button.getText().toString())) {
            finish();
        }
        if ("使用".equals(button.getText().toString())) {
            if (isEditOk())
                saveData(true);
        }
        if ("确定".equals(button.getText().toString())) {
            if (isEditOk())
                saveData(false);
        }
    }

    private boolean isEditOk() {
        if (editTexts.get(0).getText().toString().equals("")) {
            editTexts.get(0).setError("请输入编码");
            editTexts.get(0).requestFocus();
            MyUtil.showToast(this, "请输入编码");
            return false;
        }
        if (editTexts.get(1).getText().toString().equals("")) {
            editTexts.get(1).setError("请输入序列号");
            editTexts.get(1).requestFocus();
            MyUtil.showToast(this, "请输入序列号");
            return false;
        }
        if (editTexts.get(2).getText().toString().equals("")) {
            editTexts.get(2).setError("请输入身高");
            editTexts.get(2).requestFocus();
            MyUtil.showToast(this, "请输入身高");
            return false;
        }
        int num = Integer.valueOf(editTexts.get(2).getText().toString());
        if (num < 60 || num > 250) {
            editTexts.get(2).setError("身高范围：60-250");
            editTexts.get(2).requestFocus();
            MyUtil.showToast(this, "身高输入有误");
            return false;
        }
        if (editTexts.get(3).getText().toString().equals("")) {
            editTexts.get(3).setError("请输入体重");
            editTexts.get(3).requestFocus();
            MyUtil.showToast(this, "请输入体重");
            return false;
        }
        num = Integer.valueOf(editTexts.get(3).getText().toString());
        if (num < 10 || num > 250) {
            editTexts.get(3).setError("体重范围：10-250");
            editTexts.get(3).requestFocus();
            MyUtil.showToast(this, "体重输入有误");
            return false;
        }
        if (editTexts.get(4).getText().toString().equals("")) {
            editTexts.get(4).setError("请输入年龄");
            editTexts.get(4).requestFocus();
            MyUtil.showToast(this, "请输入年龄");
            return false;
        }
        num = Integer.valueOf(editTexts.get(4).getText().toString());
        if (num < 5 || num > 120) {
            editTexts.get(4).setError("年龄范围：5-120");
            editTexts.get(4).requestFocus();
            MyUtil.showToast(this, "年龄输入有误");
            return false;
        }
        for (int i = 0; i < radioGroups.size(); i++) {
            if (radioGroups.get(i).getCheckedRadioButtonId() == -1) {
                if (i == 0)
                    MyUtil.showToast(this, "请选择性别");
                else
                    MyUtil.showToast(this, "请回答第" + i + "项");
                return false;
            }
        }
        return true;
    }

    private void loadData() {
        for (int i = 0; i < editTexts.size(); i++) {
            editTexts.get(i).setText(record.editText.get(i));
        }
        for (int i = 0; i < radioButtons.size(); i++) {
            radioButtons.get(i).setChecked(record.radioChecks.get(i));
        }
        for (int i = 0; i < checkBoxes.size(); i++) {
            checkBoxes.get(i).setChecked(record.boxChecks.get(i));
        }
        record.editText.clear();
        record.radioChecks.clear();
        record.boxChecks.clear();
    }

    private void saveData(boolean isUse) {
        for (int i = 0; i < editTexts.size(); i++) {
            record.editText.add(editTexts.get(i).getText().toString());
        }
        for (int i = 0; i < radioButtons.size(); i++) {
            record.radioChecks.add(radioButtons.get(i).isChecked());
        }
        for (int i = 0; i < checkBoxes.size(); i++) {
            record.boxChecks.add(checkBoxes.get(i).isChecked());
        }
        if (recordPath == null) {
            String path;
            if (UserInfoRecord.save(record, path=Constant.userStorePath
                    + "/"
                    + editTexts.get(0).getText().toString()
                    + "-"
                    + editTexts.get(1).getText().toString()
                    + "-"
                    + System.currentTimeMillis()
                    + Constant.userEndName)) {
                if (isUse) {
                    Intent intent = new Intent();
                    intent.putExtra("userName", editTexts.get(0).getText().toString() + "   " + editTexts.get(1).getText().toString());
                    intent.putExtra("userPath", path);
                    setResult(Activity.RESULT_OK, intent);
                } else
                    setResult(Activity.RESULT_OK);
                finish();
            }
        } else {
            if (UserInfoRecord.save(record, recordPath)) {
                File temp;
                new File(recordPath).renameTo(temp = new File(Constant.userStorePath
                        + "/"
                        + editTexts.get(0).getText().toString()
                        + "-"
                        + editTexts.get(1).getText().toString()
                        + "-"
                        + System.currentTimeMillis()
                        + Constant.userEndName));
                if (isUse) {
                    Intent intent = new Intent();
                    intent.putExtra("userName", editTexts.get(0).getText().toString() + "   " + editTexts.get(1).getText().toString());
                    intent.putExtra("userPath", temp.getPath());
                    setResult(Activity.RESULT_OK, intent);
                } else
                    setResult(Activity.RESULT_OK);
                finish();
            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}
